package me.zhengjie.modules.web.service.pay.order;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.ExamOrder;
import me.zhengjie.modules.system.domain.GroupTest;
import me.zhengjie.modules.system.domain.GroupTestDetail;
import me.zhengjie.modules.system.domain.WxUser;
import me.zhengjie.modules.system.service.AtmrService;
import me.zhengjie.modules.system.service.ExamOrderService;
import me.zhengjie.modules.system.service.WxUserService;
import me.zhengjie.modules.system.service.dto.AtmrDto;
import me.zhengjie.modules.system.service.dto.ExamOrderDto;
import me.zhengjie.modules.web.domain.pay.OrderSubmitRequest;
import me.zhengjie.modules.web.domain.pay.OrderSubmitResponse;
import me.zhengjie.modules.web.domain.test.VerifyGroupTestRespDTO;
import me.zhengjie.modules.web.enums.ExamOrderTypeEnum;
import me.zhengjie.modules.web.enums.OrderStatusEnum;
import me.zhengjie.modules.web.service.ITestingService;
import me.zhengjie.modules.web.service.mybatisplus.IGroupTestDetailPlusService;
import me.zhengjie.modules.web.service.mybatisplus.IGroupTestPlusService;
import me.zhengjie.modules.web.service.order.IOrderService;
import me.zhengjie.modules.web.service.pay.IOrderSubmitService;
import me.zhengjie.modules.weixin.utils.OrderUtil;
import me.zhengjie.request.ATMRContext;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.enums.OrderPrefixEnum;
import me.zhengjie.utils.enums.OrderTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class ExamOrderSubmitServiceImpl implements IOrderSubmitService {
    @Autowired
    private ExamOrderService examOrderService;

    @Autowired
    private AtmrService atmrService;

    @Autowired
    private ITestingService testingService;

    @Autowired
    private IGroupTestPlusService groupTestPlusService;

    @Autowired
    private IGroupTestDetailPlusService groupTestDetailPlusService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    WxUserService wxUserService;


    @Override
    public int orderType() {
        return OrderTypeEnum.Exam.getOrderType();
    }

    @Override
    public OrderSubmitResponse execute(OrderSubmitRequest request) {
        if (StringUtils.isBlank(request.getAtmrId())){
            throw new WeChatException("缺少参数atmrId");
        }
        AtmrDto atmrDto = atmrService.findById(Integer.valueOf(request.getAtmrId()));
        if (Objects.isNull(atmrDto)){
            throw new WeChatException("参数传递有误");
        }
        BigDecimal orderAmount = new BigDecimal(atmrDto.getPrice());
        Integer groupId = request.getGroupId();
        boolean needUpdateGroup = false;
        if (Objects.nonNull(groupId)){
            VerifyGroupTestRespDTO respDTO = testingService.verifyGroupTesting(groupId,request.getGroupCode());
            if (Objects.nonNull(respDTO) && respDTO.isCanBeUsed()){
                orderAmount = respDTO.getTestingPrice();
                needUpdateGroup = true;
            }
        }
        String orderSn = OrderUtil.GetOrderNumber(OrderPrefixEnum.Exam.getPrefix());
        ExamOrder examOrder = new ExamOrder();
        examOrder.setOrderAmount(orderAmount);
        examOrder.setAtmrId(request.getAtmrId());
        examOrder.setOpenId(ATMRContext.getContext().getOpenId());
        examOrder.setOrderNo(orderSn);
        examOrder.setTeamTestid(groupId);
        examOrder.setBeAnswer(0);
        examOrder.setCreateTime(DateUtil.TimestampNow());
        examOrder.setPayStatus(OrderStatusEnum.WaitingPay.getOrderStatus());
        examOrder.setOrderStatus(OrderStatusEnum.WaitingPay.getOrderStatus());
        examOrder.setPayAmount(BigDecimal.ZERO);
        examOrder.setDiscountAmount(BigDecimal.ZERO);
        examOrder.setPaySerialid("");
        examOrder.setPrePayid("");
        examOrder.setOrderType(ExamOrderTypeEnum.Testing.getExamOrderType());
        Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now().plusMinutes(ConstantUtils.DefaultExpireTime));
        examOrder.setExpireTime(timestamp);
        if (orderAmount.compareTo(BigDecimal.ZERO) == 0){
            examOrder.setPayStatus(OrderStatusEnum.Payed.getOrderStatus());
            examOrder.setOrderStatus(OrderStatusEnum.Payed.getOrderStatus());
        }
        WxUser wxUser = wxUserService.findByOpenId(examOrder.getOpenId());
        if(!ObjectUtil.isEmpty(wxUser)){
            examOrder.setWxRealName(wxUser.getRealName());
            examOrder.setWxName(wxUser.getNickname());
        }
        ExamOrderDto examOrderDto = examOrderService.create(examOrder);
        OrderSubmitResponse response = new OrderSubmitResponse();
        response.setOrderId(examOrderDto.getOrderId());
        response.setOrderSn(orderSn);
        response.setOrderStatus(examOrder.getOrderStatus());

        //创单就减掉团体测评库存
        if (Objects.nonNull(groupId) && needUpdateGroup){
            if (StringUtils.isNotBlank(request.getGroupCode())){
                UpdateWrapper<GroupTestDetail> updateWrapper = Wrappers.update();
                updateWrapper.setSql("tested=tested+1").eq("serial_code",request.getGroupCode());
                groupTestDetailPlusService.update(updateWrapper);
            }else {
                UpdateWrapper<GroupTest> updateWrapper = Wrappers.update();
                updateWrapper.setSql("limit_used=limit_used+1").eq("id",groupId);
                groupTestPlusService.update(updateWrapper);
            }
        }
        orderService.orderExpire2Redis(orderType(),orderSn,timestamp);
        return response;
    }
}
